package com.sdk.springbootdapr.controller;

import io.dapr.client.DaprClient;
import io.dapr.client.domain.ConfigurationItem;
import io.dapr.client.domain.SubscribeConfigurationResponse;
import io.dapr.client.domain.UnsubscribeConfigurationResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class DaprConfigController {

    private final DaprClient daprClient;
    private static final String DAPR_CONFIGURATON_STORE = "configstore";
    private static List<String> CONFIGURATION_ITEMS = List.of("orderId1", "orderId2");
    private static String subscriptionId = null;

    public DaprConfigController(DaprClient daprClient) {
        this.daprClient = daprClient;
    }

    @GetMapping("/get-config")
    public Map<String, String> getConfig() {
        Map<String, String> configMap = new HashMap<>();
        for (String configurationItem : CONFIGURATION_ITEMS) {
            ConfigurationItem item = daprClient.getConfiguration(DAPR_CONFIGURATON_STORE, configurationItem).block();
            configMap.put(configurationItem, item.getValue());
        }
        return configMap;
    }

    @GetMapping("/subscribe-config")
    public String subscribeConfig() throws InterruptedException {
        StringBuilder result = new StringBuilder();
        Flux<SubscribeConfigurationResponse> subscription = daprClient.subscribeConfiguration(DAPR_CONFIGURATON_STORE,
                CONFIGURATION_ITEMS.toArray(String[]::new));
        subscription.subscribe((response) -> {
            // First ever response contains the subscription id
            if (response.getItems() == null || response.getItems().isEmpty()) {
                subscriptionId = response.getSubscriptionId();
                result.append("订阅id: ").append(subscriptionId).append("没有发生改变\n");
            } else {
                response.getItems().forEach((k, v) -> {
                    result.append("配置key ").append(k).append(": {'value':'").append(v.getValue()).append("'}\n");
                });
            }
        });
        Thread.sleep(20000);
        return result.toString();
    }

    @GetMapping("/unsubscribe-config")
    public String unsubscribeConfig() throws InterruptedException {
        StringBuilder result = new StringBuilder();
        UnsubscribeConfigurationResponse unsubscribe = daprClient
                .unsubscribeConfiguration(subscriptionId, DAPR_CONFIGURATON_STORE).block();
        if (unsubscribe.getIsUnsubscribed()) {
            result.append("取消订阅成功");
        } else {
            result.append("取消订阅失败，异常为:").append(unsubscribe.getMessage());
        }
        return result.toString();
    }
}
